package com.yupi.springbootinit.service.production;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.springbootinit.mapper.WorkflowTaskMapper;
import com.yupi.springbootinit.model.entity.WorkflowTask;
import com.yupi.springbootinit.model.entity.ProcessBatch;
import com.yupi.springbootinit.mapper.ProcessBatchMapper;
import com.yupi.springbootinit.model.vo.production.ProductionTaskCardVO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生产部（SC001）任务卡片查询服务
 */
@Service
public class ProductionCardQueryService {

    private static final Set<String> ALLOW_TASK_TYPES = new HashSet<>(Arrays.asList(
            "PRODUCTION_PREP_CLEANING",
            "PRODUCTION_WORKORDER"
    ));

    @Resource
    private WorkflowTaskMapper workflowTaskMapper;

    @Resource
    private ProcessBatchMapper processBatchMapper;

    /**
     * 分页查询我的生产卡片（仅 SC001 部门）
     */
    public Page<ProductionTaskCardVO> pageMyProductionCards(Long userId, Long departmentId, String departmentCode, long current, long size) {
        // 部门校验（若传入 departmentCode 则严格校验为 SC001）
        if (departmentCode != null && !"SC001".equalsIgnoreCase(departmentCode)) {
            return new Page<>(current, size, 0);
        }
        // 查询当前部门的生产类任务（我的：claimedBy = userId 或未认领但归属部门为当前部门）
        LambdaQueryWrapper<WorkflowTask> qw = new LambdaQueryWrapper<>();
        qw.eq(WorkflowTask::getIsDelete, 0)
          .eq(WorkflowTask::getBizType, "PROCESS_BATCH")
          .eq(departmentId != null, WorkflowTask::getDepartmentId, departmentId)
          .in(WorkflowTask::getTaskType, ALLOW_TASK_TYPES)
          // 个人任务：已认领人为当前用户 或 未认领但属于当前部门（这里优先筛已认领）
          .and(userId != null, w -> w.eq(WorkflowTask::getClaimedBy, userId).or(o -> o.isNull(WorkflowTask::getClaimedBy)));

        Page<WorkflowTask> taskPage = new Page<>(current, size);
        List<WorkflowTask> tasks = workflowTaskMapper.selectPage(taskPage, qw).getRecords();
        List<ProductionTaskCardVO> cards = Collections.emptyList();

        if (tasks != null && !tasks.isEmpty()) {
            // 批量查询批次信息
            Set<Long> batchIds = tasks.stream()
                    .filter(t -> t.getBizId() != null)
                    .map(WorkflowTask::getBizId)
                    .collect(Collectors.toSet());
            Map<Long, ProcessBatch> batchMap = new HashMap<>();
            if (!batchIds.isEmpty()) {
                LambdaQueryWrapper<ProcessBatch> pbQw = new LambdaQueryWrapper<>();
                pbQw.in(ProcessBatch::getId, batchIds);
                List<ProcessBatch> batches = processBatchMapper.selectList(pbQw);
                if (batches != null) {
                    for (ProcessBatch b : batches) {
                        batchMap.put(b.getId(), b);
                    }
                }
            }
            cards = tasks.stream().map(t -> toCard(t, batchMap.get(t.getBizId()))).collect(Collectors.toList());
        }

        Page<ProductionTaskCardVO> cardPage = new Page<>(current, size, taskPage.getTotal());
        cardPage.setRecords(cards);
        return cardPage;
    }

    private ProductionTaskCardVO toCard(WorkflowTask t, ProcessBatch b) {
        ProductionTaskCardVO vo = new ProductionTaskCardVO();
        vo.setTaskId(t.getId());
        vo.setTaskTitle(t.getTaskTitle());
        vo.setTaskStatus(t.getTaskStatus());
        vo.setProductName(t.getProductName());
        vo.setBatchCode(b != null ? b.getBatchCode() : null);
        vo.setPowderModel(b != null ? b.getPowderModel() : null);
        vo.setPowderWeight(b != null ? b.getPowderWeight() : null);
        vo.setCleaningDevice(b != null ? b.getCleaningDeviceName() : null);
        vo.setEquipmentStatus(null); // 设备状态暂不返回

        // 开始时间：优先 handleStartTime（暂未引入），其次 claimedTime
        LocalDateTime start = t.getClaimedTime();
        vo.setStartTime(start != null ? start.toString() : null);

        // 进行中时长：仅在 IN_PROGRESS 时计算
        if ("IN_PROGRESS".equals(t.getTaskStatus()) && start != null) {
            long seconds = Duration.between(start, LocalDateTime.now()).getSeconds();
            vo.setRunDurationSeconds(Math.max(seconds, 0));
        } else {
            vo.setRunDurationSeconds(null);
        }
        return vo;
    }
}